<script>
	import Vue from 'vue'
	import config from '@/common/config'
	import store from '@/store'
	import {
		UpdateApp,
		user,
		DB,
		PushMsg
	} from '@/common/framework';
	//#ifdef APP-PLUS
	const LcPush = uni.requireNativePlugin('lc-push');
	//#endif
	export default {
		globalData: config,
		data() {
			return {
				curUserInfo:{},
				pushMsg: null
			}
		},
		onLaunch: function() {
			this.checkLogin();
			this.curUserInfo =  user.getUserInfo();
			this.pushMsg = PushMsg.init();
			// #ifdef APP-PLUS
			plus.screen.lockOrientation('portrait-primary'); //锁定屏幕方向
			UpdateApp.init().checkUpdate(); //版本检查
			this.bindNotificationPush();
			this.loadIcon();
			this.initDb();
			// #endif

			//#ifdef H5
			this.initDb();
			//#endif



		},
		onShow: function() {
			console.log('App Show');
			store.commit('setAppState','app-show');

			this.bindMessagePush();
			// #ifdef APP-PLUS
			plus.push.setAutoNotification( false );
			// #endif
		},

		onHide: function() {
			console.log('App Hide');
			store.commit('setAppState','app-hide');

			// #ifdef APP-PLUS
			//this.pushMsg.disConnent();
			plus.push.setAutoNotification( true );
			// #endif
		},
		computed: {
			hasLogin: () => {
				return store.getters.hasLogin;
			}
		},
		watch: {
			'hasLogin': function(newVer, oldVer) {

				if (newVer) {
				
					if (this.pushMsg.IsConnent) {
						console.log("已经登录，设置别名");
						this.setClientInfo();
					}
				} else {
					if (this.pushMsg.IsConnent) {
						this.pushMsg.removeAlias();
					}
				}
			}
		},
		methods: {


			loadIcon: function() {
				//引入字体图标
				var domModule = weex.requireModule('dom');
				domModule.addRule('fontFace', {
					'fontFamily': "uniicons",
					'src': "url('~@/static/css/font/uni.ttf')"
				});

				domModule.addRule('fontFace', {
					'fontFamily': "factory",
					'src': "url(''~@/static/css/font/factory.ttf')"
				});
				domModule.addRule("fontFace", {
					'fontFamily': "goodsManageIcon",
					'src': "url(''~@/static/css/font/goodsmanage.ttf')"
				});
			},

			checkLogin: function() {
				// uni.switchTab({
				// 	url: '/pages/work/index/index'
				// })
				if (!user.checkLogin()) {
					uni.reLaunch({
						url: '/pages/user/login/login'
					})
				} else {
					uni.switchTab({
						url: '/pages/work/index/index'
					})
				}
			},

			initDb: function() {
				let db = DB.init("push-msg");
				let dbVer = 1; //当有数据修改的时候，这里需要加1
				let createTableSqlArray = []; //创建表结构的sql
				let alterTableSqlArray = []; //修改表结构的sql
				createTableSqlArray.push(
					"create table if not exists topic(t_id NVARCHAR(36) PRIMARY KEY NOT NULL UNIQUE,t_isTop INT ,t_msgType NVARCHAR(10), t_userId NVARCHAR(36),t_senderId NVARCHAR(36), t_type INT,t_unReadCount INT, t_title NVARCHAR(50),t_content NVARCHAR(50), t_icon NVARCHAR(100),  t_time INTEGER DEFAULT 0  )"
				);
				//alterTableSqlArray.push("drop table topic");//删除表
				db.initDB(dbVer, 'topic', createTableSqlArray, alterTableSqlArray).then(() => {
					console.log('数据库初始化成功');
				}).catch(e => {
					console.error('数据库初始化失败,' + JSON.stringify(e));
				});
			},
			setClientInfo() {
				let curUserInfo = user.getUserInfo();
				this.pushMsg.setClientInfo(curUserInfo.userRealName, curUserInfo.headerImg);
				this.pushMsg.setAlias(curUserInfo.userId);
			},
			bindMessagePush: async function() {

				if (!this.pushMsg.IsConnent) {
					this.pushMsg.initPush().then(ret => {
						if (ret) {
							console.log('推送服务初始化成功');
							uni.showToast({
								title: "推送服务初始化成功",
								icon: 'none',
								position: 'bottom'
							})
							this.setClientInfo();
						}
					}).catch(err => {
						console.log(err);
					});
				} else {
					
					this.setClientInfo();
				}

			},

			bindNotificationPush: function() {
				var options = {
					msgPush:config.msgPush,
					isUseLocalPush:false,//是否使用本地的push服务
					// mqttHost: "tcp://" + config.msgPush.mqttHost + ":" + config.msgPush.mqttPort,
					// webApiBaseUrl: config.msgPush.webApi,
					appId: config.appId, //当前应用的APPID
					isWakeUp: true, //收到消息是否唤醒屏幕
					serverIsForeground: true, //设置为前台服务
					isNotionMore: false, //是否只显示最新消息
					userName: '',
					userPassword: '',
					label: 'notification',
					cleanSession: false,
					reconnect: true,
					deviceId: this.pushMsg.devCode,
					connectionTimeout: 10,
					keepAliveInterval: 10,
					isSaveLog: true,
					transTypeItems: [{
							isLock: 0, //0:不锁屏；1:锁屏
							appState: 1, //0:退出；1:在前台；2:在后台
							type: 10, //消息类型
							isRing: false, //使用内置通知铃声
							isMedia: false, //使用自定义铃声
							ringPath: "/static/ring/mo_meeting_push_ring2.mp3",
							isAutoOpenApp: false, //是否自动开启App
							isPutNotification: false //是否弹出通知栏消息
						},
						{
							isLock: 0, //未锁屏
							appState: 1, 
							type: 11,
							isRing: false,
							isMedia: false,
							ringPath: "/static/ring/mo_meeting_push_ring2.mp3",
							isAutoOpenApp: false,
							isPutNotification: false
						},
						{
							isLock: 0, //未锁屏
							appState: 1, 
							type: 12,
							isRing: false,
							isMedia: false,
							ringPath: "/static/ring/mo_meeting_push_ring2.mp3",
							isAutoOpenApp: false,
							isPutNotification: false
						}
					]
				};
				//#ifdef APP-PLUS
				LcPush.initMQTTNtion(options, this.reciveMsg);
				//#endif
			},
			reciveMsg(data) {
				uni.showToast({
					title: JSON.stringify(data),
					icon: 'none',
					position: 'bottom'
				});
				console.log("notification",JSON.stringify(data));
				
				// switch(data.type){
				// 	case "connect":
				// 	LcPush.setAlias(this.curUserInfo.clientId,this.curUserInfo.userId);
				// 	break;
				// }
				
				
			}

		}

	}
</script>

<style>
	/*每个页面公共css */
	@import './static/css/uni.css';
	@import './components/other-com/ly-tree/ly-tree.css';
	@import "./static/css/thorui.css";
	@import "./static/css/app.scss";
</style>
